package cn.lovemmd.model.service.Impl;

import cn.lovemmd.model.dto.LoginResult;
import cn.lovemmd.model.mapper.UserMapper;
import cn.lovemmd.model.pojo.SysUser;
import cn.lovemmd.model.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    
    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //登录
    @Override
    public SysUser login(String name, String password) {
        return userMapper.selectByNameAndPassword(name, password);
    }
    
    /**
     * 新版登录方法（返回详细结果）
     */
    @Override
    public LoginResult loginWithResult(String name, String password) {
        try {
            // 1. 首先检查用户是否存在
            SysUser user = userMapper.selectByName(name);
            if (user == null) {
                log.warn("登录失败：用户不存在 - {}", name);
                return LoginResult.failure(LoginResult.LoginErrorType.USER_NOT_FOUND);
            }
            
            // 2. 检查用户状态
            Integer status = user.getUStatus();
            if (status != null && status != 0) {
                log.warn("登录失败：账号已被禁用 - {}, 状态: {}", name, status);
                return LoginResult.failure(LoginResult.LoginErrorType.ACCOUNT_DISABLED, 
                    "当前账号已被禁用，请联系管理员！");
            }
            
            // 3. 验证密码
            SysUser authenticatedUser = userMapper.selectByNameAndPassword(name, password);
            if (authenticatedUser == null) {
                log.warn("登录失败：密码错误 - {}", name);
                return LoginResult.failure(LoginResult.LoginErrorType.PASSWORD_INCORRECT);
            }
            
            // 4. 登录成功
            log.info("用户登录成功: {}", name);
            return LoginResult.success(authenticatedUser);
            
        } catch (Exception e) {
            log.error("登录异常: {}", e.getMessage(), e);
            return LoginResult.failure(LoginResult.LoginErrorType.UNKNOWN_ERROR, 
                "登录过程中发生错误，请稍后重试");
        }
    }

    @Override
    public Integer register(String name, String password, String code,String qq) {
        return userMapper.addUser(name, password, code,qq);
    }

    @Override
    public Integer findUser(String name) {
        return userMapper.findUser(name);
    }

    @Override
    public Integer getUserStatus(String name) {
        return userMapper.getUserStatus(name);
    }
}
